package com.uinnova.product.eam.init.cassso;

import com.uinnova.product.eam.config.CacheKeyPrefix;
import com.uino.bean.permission.base.SysUser;
import com.uino.util.cache.ICacheService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description
 *
 * @author lichong
 * @since 2022/5/13 10:18
 */
@Component
@Log4j2
@ConditionalOnProperty(name = "monet.login.loginMethod", havingValue = "guotouiam")
public class CASUserOnlineInterceptor implements HandlerInterceptor {

    @Autowired
    private ICacheService cacheService;

    @Autowired
    private CASCurrentUser casCurrentUser;

    @Value("${uino.token.online.time:30}")
    private Integer sessionOnlineTime;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String currentToken = casCurrentUser.getCurrentToken();
        if (StringUtils.isBlank(currentToken)) {
            return true;
        }
        SysUser sysUser = casCurrentUser.getCurrentUserInfo(currentToken);
        if (sysUser == null) {
            return true;
        }
        cacheService.setCache("cas:ticket" + ":" + currentToken, sysUser.getLoginCode(), sessionOnlineTime * 60 * 1000);
        cacheService.setCache(CacheKeyPrefix.UINO_USER_ONLINE_PREFIX + ":" + sysUser.getLoginCode(), "", sessionOnlineTime * 60 * 1000);
        return true;
    }
}
